package websocketUtils

import (
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
	"utilsx/entity"
	"utilsx/ginRoute"
)

type WebsocketServer struct {
	port     string
	upgrader websocket.Upgrader
	conns    map[*websocket.Conn]bool //全局连接池 保存的 与 test conn
	connSet  entity.Set[*websocket.Conn, any]
	reader   WsMsg
}

func NewServer(port string) *WebsocketServer {
	return &WebsocketServer{
		port:     port,
		upgrader: websocket.Upgrader{},
		conns:    make(map[*websocket.Conn]bool),
		connSet:  entity.NewSet[*websocket.Conn, any](),
	}
}
func (ws *WebsocketServer) SetHttpHandler(path string, handler http.HandlerFunc) {
	http.HandleFunc(path, handler)
}
func (ws *WebsocketServer) ToGinHandle(handler http.HandlerFunc) gin.HandlerFunc {
	return ginRoute.GinHandler(handler)
}

//	func (ws *WebsocketServer) GetConn(ctx *gin.Context) *websocket.conn {
//		to, request := ginRoute.GinToHandler(ctx)
//		//http->ws （server）
//		conn, err := ws.upgrader.Upgrade(to, request, nil)
//		if err != nil {
//			log.Println("Error upgrading connection: ", err)
//			return nil
//		}
//		// 将新连接添加到连接池
//		ws.conns[conn] = true
//		ws.connSet.Add(conn)
//		fmt.Println("链接成功！", conn.LocalAddr(), conn.RemoteAddr())
//		return conn
//	}
func (ws *WebsocketServer) StartHttp() {
	err := http.ListenAndServe(ws.port, nil)
	if err != nil {
		log.Fatal(err)
	}
}
func (ws *WebsocketServer) Send(messageType int, data []byte, conns ...*websocket.Conn) {
	ws.reader.WriterMessage(messageType, data, conns...)
}
func (ws *WebsocketServer) ToOthers(sender *websocket.Conn, targetClient ...*websocket.Conn) {
	// 循环读取客户端发送的消息，并将其广播给其他客户端
	for {
		var msg WebsocketMsgClaims
		err := sender.ReadJSON(&msg)
		if err != nil {
			// 删除断开连接的客户端
			delete(ws.conns, sender)
			log.Println("Error reading message: ", err)
			break
		}
		log.Println(sender.LocalAddr(), "GetMsg:", msg)
		// 广播消息给所有客户端
		for _, client := range targetClient {
			if client != sender {
				err := client.WriteJSON(msg)
				if err != nil {
					log.Println("Error broadcasting message: ", err)
				}
			}
		}
	}
}
func (ws *WebsocketServer) Watch() {

}
